/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlets;

import Beans.Ciudad;
import Beans.Hotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Micaela
 */
public class AltaHabitacion extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
     private Connection con;
     @Override
     public void init() throws ServletException{
        try{
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://localhost/Agencia","root","root");
        }
        catch(Exception ex){
            throw new UnavailableException("Error al intentar conectar con la bd :(: "+ex.getMessage());
        }
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
       
        PrintWriter out = response.getWriter();
        String NomHotel, Pais, Ciudad, Tipo;
        int NumHabitacion, Capacidad;
        Ciudad c; Hotel h;
        double Precio;
        
         if(request.getParameter("NomHotel")!=null && request.getParameter("Pais")!=null
                    && request.getParameter("Ciudad")!=null && request.getParameter("NumHabitacion")!=null
                 && request.getParameter("Tipo")!=null && request.getParameter("Capacidad")!= null
                 && request.getParameter("Precio")!= null){
             try {
                    NomHotel = request.getParameter("NomHotel");
                    Pais = request.getParameter("Pais");
                    Ciudad = request.getParameter("Ciudad");
                    NumHabitacion = Integer.parseInt(request.getParameter("NumHabitacion"));
                    Tipo = request.getParameter("Tipo");
                    Capacidad = Integer.parseInt(request.getParameter("Capacidad"));
                    Precio = Double.parseDouble(request.getParameter("Precio"));
                    c = BuscarCiudad(Ciudad, Pais);
                    h = BuscarHotel(c,NomHotel);
                    if(h!=null){                    
                    CallableStatement cs= con.prepareCall("{call AltaHabitacion(?,?,?,?,?)}");
                    cs.setInt(1, NumHabitacion);
                    cs.setInt( 2, h.getIdHotel() );
                    cs.setString( 3, Tipo );
                    cs.setInt( 4, Capacidad); 
                    cs.setDouble(5, Precio);
                    cs.executeUpdate();
                    response.sendRedirect("MenuPrincipal.jsp");
                    }
             }
                catch(SQLException ex){
                    out.print("Error en bd o intentar convertir -.- :("+ex.getMessage());
                }
            }        
            else{
                out.println("Por favor Ingrese todos los datos necesarios para dar el alta a la habitación");
                out.println("<a href=\"AltaHabitacion.jsp\">Volver</a>");
            }
         }
  
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
      public Ciudad BuscarCiudad(String pNombre, String pPais) throws SQLException{
        try{
            CallableStatement cs=con.prepareCall("{call BuscarCiudad(?,?)}");
                  cs.setString(1, pNombre);
                  cs.setString(2, pPais);
                  ResultSet rs=cs.executeQuery();                  
                  Ciudad c=null;
                  if(rs.next()){
                      c=new Ciudad(rs.getString("Nombre"), rs.getString("Pais"), rs.getString("IdiomaOf"));
                      c.setCodCiudad(rs.getInt("CodCiudad"));
                  }       
                  return c;
        }
        catch(SQLException ex){
            throw ex;
        }
    }
      public Hotel BuscarHotel(Ciudad c, String NomHotel) throws UnavailableException{
   
   try {            
                CallableStatement cs= con.prepareCall("{call BuscarHotel(?,?)}");                
                cs.setInt(1, c.getCodCiudad());
                cs.setString(2, NomHotel);
                ResultSet rs = cs.executeQuery();
                 Hotel h=null;
              if(rs.next()){
                     h = new Hotel(rs.getString("Nombre"),rs.getInt("Clasificacion"),null,c);
                     h.setIdHotel(rs.getInt("IdHotel")); 
                     Blob blob=rs.getBlob("Foto");
                     if(blob!=null){
                     byte[] data=blob.getBytes(1, (int)blob.length());
                     h.setUnaFoto(data);
                     }
              }              
        return h;
        }
    catch (SQLException ex){
                throw new UnavailableException("Error! :" + ex.getMessage());
            }
    
    }

}
